<template>
    <div class="pacu-container">
        <!-- 查询表单 -->
        <a-form class="smart-query-form">
            <a-row class="smart-query-form-row">
                <a-form-item label="入PACU时间" class="smart-query-form-item">
                    <a-range-picker v-model:value="dateRange" :presets="defaultTimeRanges" @change="dateRangeChange" 
                        show-time format="YYYY-MM-DD HH:mm:ss" />
                </a-form-item>
                <a-form-item class="smart-query-form-item smart-margin-left10">
                    <a-button-group>
                        <a-button type="primary" @click="onSearch">
                            <template #icon><SearchOutlined /></template>
                            查询
                        </a-button>
                        <a-button @click="resetQuery">
                            <template #icon><ReloadOutlined /></template>
                            重置
                        </a-button>
                    </a-button-group>
                </a-form-item>
            </a-row>
        </a-form>

        <a-card size="small" :bordered="false" :hoverable="true">
            
        <div class="pacu-instructions">
            <p>1. 填写在PACU工作的时间</p>
            <p>2. 系统自动根据时间范围同步患者信息</p>
        </div>

        <a-form :model="pacuForm" layout="inline" class="pacu-time-form">
            <a-form-item label="开始时间">
                <a-date-picker
                    v-model:value="pacuForm.startTime"
                    show-time
                    format="YYYY-MM-DD"
                    placeholder="选择开始时间"
                />
            </a-form-item>
            <a-form-item label="结束时间">
                <a-date-picker
                    v-model:value="pacuForm.endTime"
                    show-time
                    format="YYYY-MM-DD"
                    placeholder="选择结束时间"
                />
            </a-form-item>
            <a-form-item>
                <a-button type="primary" @click="savePacuTime">
                    <template #icon><SaveOutlined /></template>
                    保存
                </a-button>
            </a-form-item>

        </a-form>
        </a-card>
        <br/>


        <!-- 表格区域 -->
        <a-card size="small" :bordered="false" :hoverable="true">
            <a-row class="smart-table-btn-block">
                <div class="smart-table-operate-block">
                    <a-button type="primary" @click="showPacuModal()">
                        <template #icon><PlusOutlined /></template>
                        新增
                    </a-button>
                </div>
                <div class="smart-table-setting-block">
                    <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.pacu.pacu" :refresh="queryData" />
                </div>
            </a-row>

            <a-table 
                size="small" 
                class="ant-table-striped" 
                :columns="columns" 
                :data-source="tableData"
                :loading="tableLoading" 
                :pagination="false" 
                rowKey="id" 
                bordered 
                :scroll="{ x: 1300 }"
                :row-className="(record, index) => (index % 2 === 1 ? 'table-striped' : null)">
                
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'action'">
                        <a-space>
                            <a-button @click="editPacu(record)" size="small" type="link">编辑</a-button>
                            <a-popconfirm
                                title="确定要删除这条记录吗？"
                                @confirm="deletePacu(record)"
                                ok-text="确定"
                                cancel-text="取消">
                                <a-button size="small" type="link" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                    <template v-else-if="column.dataIndex === 'inPacuDateTime' || column.dataIndex === 'outPacuDateTime'">
                        {{ record[column.dataIndex] ? dayjs(record[column.dataIndex]).format('YYYY-MM-DD HH:mm:ss') : '-' }}
                    </template>
                </template>
            </a-table>

            <!-- 分页 -->
            <div class="smart-query-table-page">
                <a-pagination 
                    v-model:current="queryForm.pageNum"
                    v-model:pageSize="queryForm.pageSize"
                    :total="total"
                    show-size-changer
                    show-quick-jumper
                    @change="handlePageChange"
                    :page-size-options="PAGE_SIZE_OPTIONS"
                    :show-total="(total) => `共${total}条`" />
            </div>
        </a-card>

        <!-- PACU表单模态框 -->
        <a-modal
            v-model:open="modalVisible"
            :title="formState.id ? '编辑PACU记录' : '新增PACU记录'"
            width="800px"
            @ok="handleSubmit"
            @cancel="closeModal"
            :confirmLoading="submitLoading"
        >
            <a-form 
                ref="formRef"
                :model="formState"
                :rules="rules"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }">
                <a-form-item label="住院号" name="inpNo" required>
                    <a-input v-model:value="formState.inpNo" placeholder="请输入住院号" />
                </a-form-item>
                <a-form-item label="姓名" name="name" required>
                    <a-input v-model:value="formState.name" placeholder="请输入姓名" />
                </a-form-item>
                <a-form-item label="性别" name="sex" required>
                    <a-radio-group v-model:value="formState.sex">
                        <a-radio value="1">男</a-radio>
                        <a-radio value="2">女</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="年龄" name="age" required>
                    <a-input-number v-model:value="formState.age" :min="0" :max="150" style="width: 100%" />
                </a-form-item>
                <a-form-item label="复苏床号" name="pacuBedNo" required>
                    <a-input v-model:value="formState.pacuBedNo" placeholder="请输入复苏床号" />
                </a-form-item>
                <a-form-item label="手术名称" name="operationName" required>
                    <a-textarea v-model:value="formState.operationName" :rows="2" placeholder="请输入手术名称" />
                </a-form-item>
                <a-form-item label="入PACU时间" name="inPacuDateTime" required>
                    <a-date-picker 
                        v-model:value="formState.inPacuDateTime"
                        show-time
                        format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                        placeholder="请选择入PACU时间" />
                </a-form-item>
                <a-form-item label="出PACU时间" name="outPacuDateTime">
                    <a-date-picker 
                        v-model:value="formState.outPacuDateTime"
                        show-time
                        format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                        placeholder="请选择出PACU时间" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined } from '@ant-design/icons-vue';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { defaultTimeRanges } from '/@/lib/default-time-ranges';
import dayjs from 'dayjs';
import { pacuApi } from '/@/api/pacu/pacu-api';
import { encryptData } from '/@/lib/encrypt';

// 表格列定义
const columns = ref([
    {
        title: '住院号',
        dataIndex: 'inpNo',
        width: 120,
        align: 'center'
    },
    {
        title: '姓名',
        dataIndex: 'name',
        width: 100,
        align: 'center'
    },
    {
        title: '性别',
        dataIndex: 'sex',
        width: 80,
        align: 'center',
        customRender: ({ text }) => text === '1' ? '男' : '女'
    },
    {
        title: '年龄',
        dataIndex: 'age',
        width: 80,
        align: 'center'
    },
    {
        title: '复苏床号',
        dataIndex: 'pacuBedNo',
        width: 100,
        align: 'center'
    },
    {
        title: '手术名称',
        dataIndex: 'operationName',
        width: 200,
        align: 'center'
    },
    {
        title: '入PACU时间',
        dataIndex: 'inPacuDateTime',
        width: 180,
        align: 'center'
    },
    {
        title: '出PACU时间',
        dataIndex: 'outPacuDateTime',
        width: 180,
        align: 'center'
    },
    {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        width: 150,
        align: 'center'
    }
]);

// 查询表单数据
const queryForm = reactive({
    pageNum: 1,
    pageSize: 10,
    startTime: '',
    endTime: ''
});

const pacuForm = ref({
    id: undefined,
    startTime: "",
    endTime: "",
});

// 表格数据
const tableData = ref([]);
const tableLoading = ref(false);
const total = ref(0);

// 日期范围
const dateRange = ref([]);

// 表单数据
const modalVisible = ref(false);
const submitLoading = ref(false);
const formRef = ref();
const formState = reactive({
    id: '',
    inpNo: '',
    name: '',
    sex: '1',
    age: undefined,
    pacuBedNo: '',
    operationName: '',
    inPacuDateTime: null,
    outPacuDateTime: null
});

// 表单验证规则
const rules = {
    inpNo: [{ required: true, message: '请输入住院号' }],
    name: [{ required: true, message: '请输入姓名' }],
    sex: [{ required: true, message: '请选择性别' }],
    age: [{ required: true, message: '请输入年龄' }],
    pacuBedNo: [{ required: true, message: '请输入复苏床号' }],
    operationName: [{ required: true, message: '请输入手术名称' }],
    inPacuDateTime: [{ required: true, message: '请选择入PACU时间' }]
};

// 日期范围变化
function dateRangeChange(dates, dateStrings) {
    queryForm.startTime = dateStrings[0];
    queryForm.endTime = dateStrings[1];
}

// 重置查询
function resetQuery() {
    dateRange.value = [];
    queryForm.startTime = '';
    queryForm.endTime = '';
    queryData();
}

// 查询数据
function onSearch() {
    queryForm.pageNum = 1;
    queryData();
}

// 加载表格数据
async function queryData() {
    tableLoading.value = true;
    try {
        let queryParam = { encryptData: encryptData(queryForm) };
        // 实现查询逻辑
        const res = await pacuApi.getPacuList(queryParam);
        tableData.value = res.data.list;
        total.value = res.data.total;
    } catch (error) {
        message.error('加载数据失败');
    } finally {
        tableLoading.value = false;
    }
}

// 显示表单模态框
function showPacuModal(record = null) {
    modalVisible.value = true;
    if (record) {
        Object.assign(formState, {
            ...record,
            inPacuDateTime: record.inPacuDateTime ? dayjs(record.inPacuDateTime) : null,
            outPacuDateTime: record.outPacuDateTime ? dayjs(record.outPacuDateTime) : null
        });
    } else {
        resetForm();
    }
}

// 编辑记录
function editPacu(record) {
    showPacuModal(record);
}

// 删除记录
async function deletePacu(record) {
    try {
        // 实现删除逻辑
        await pacuApi.deletePacu(record.id);
        message.success('删除成功');
        queryData();
    } catch (error) {
        message.error('删除失败');
    }
}

// 关闭模态框
function closeModal() {
    modalVisible.value = false;
    resetForm();
}

// 提交表单
async function handleSubmit() {
    try {
        await formRef.value.validate();
        submitLoading.value = true;
        if (dayjs(formState.outPacuDateTime).isBefore(formState.inPacuDateTime)) {
        message.error('结束时间不能早于开始时间');
        return;
        }
        const data = {
            ...formState,
            inPacuDateTime: formState.inPacuDateTime?.format('YYYY-MM-DD HH:mm:ss'),
            outPacuDateTime: formState.outPacuDateTime?.format('YYYY-MM-DD HH:mm:ss')
        };
        let submitData = { encryptData: encryptData(data) };
        if (formState.id) {
            console.info(submitData);
            await pacuApi.updatePacu(submitData);
        } else {
            await pacuApi.createPacu(submitData);
        }
        
        message.success('保存成功');
        closeModal();
        queryData();
    } catch (error) {
        if (error.errorFields) {
            message.error('表单填写有误，请检查');
        } else {
            message.error('保存失败，请稍后重试');
        }
    } finally {
        submitLoading.value = false;
    }
}

// 处理分页变化
function handlePageChange(page, pageSize) {
    queryForm.pageNum = page;
    queryForm.pageSize = pageSize;
    queryData();
}

function resetForm() {
    Object.assign(formState, {
        id: '',
        inpNo: '',
        name: '',
        sex: '1',
        age: undefined,
        pacuBedNo: '',
        operationName: '',
        inPacuDateTime: null,
        outPacuDateTime: null
    });
}

onMounted(() => {
    queryData();
    queryPacuTime();
});
// 保存PACU工作时间
async function savePacuTime() {
    if (!pacuForm.value.startTime || !pacuForm.value.endTime) {
        message.error('请选择开始时间和结束时间');
        return;
    }

    if (dayjs(pacuForm.value.endTime).isBefore(pacuForm.value.startTime)) {
        message.error('结束时间不能早于开始时间');
        return;
    }

    try {
        const data = {
            id: pacuForm.value.id,
            startTime:dayjs(pacuForm.value.startTime).format('YYYY-MM-DD HH:mm:ss'),
            endTime:dayjs(pacuForm.value.endTime).format('YYYY-MM-DD HH:mm:ss')
        };

        let submitData = { encryptData: encryptData(data) };
        let response;
        if (data.id) {
          response  = await pacuApi.updatePacuTime(submitData);
        } else {
          response  = await pacuApi.createPacuTime(submitData);
        }
        if (response.code === 0) {
          message.success('保存成功');
          queryPacuTime();
        } else {
          message.error(response.message || '保存失败');
        }
    } catch (error) {
        message.error('保存失败，请稍后重试');
    }
}
async function queryPacuTime() {
  try {
    const res = await pacuApi.getPacuTime();
    if (res.data) {
      pacuForm.value.startTime = res.data.startTime ? dayjs(res.data.startTime) : null;
      pacuForm.value.endTime = res.data.endTime ? dayjs(res.data.endTime) : null;
      pacuForm.value.id = res.data.id;
    }
  } catch (error) {
    console.error("Failed to fetch PACU time data:", error);
  }
}
</script>

<style scoped>
.ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
}

.smart-table-btn-block {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.smart-query-table-page {
    margin-top: 16px;
    text-align: right;
}

/* 优化表单容器 */
:deep(.ant-modal-body) {
    padding: 24px;
}

/* 优化表单项间距 */
:deep(.ant-form-item) {
    margin-bottom: 16px;
}

/* 优化标签样式 */
:deep(.ant-form-item-label > label) {
    font-weight: 500;
    color: #1f1f1f;
}

/* 优化输入框样式 */
:deep(.ant-input),
:deep(.ant-input-number),
:deep(.ant-picker) {
    border-radius: 4px;
    border-color: #d9d9d9;
    transition: all 0.3s;
}

:deep(.ant-input:hover),
:deep(.ant-input-number:hover),
:deep(.ant-picker:hover) {
    border-color: #40a9ff;
}

:deep(.ant-input:focus),
:deep(.ant-input-number:focus),
:deep(.ant-picker-focused) {
    border-color: #40a9ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 优化单选按钮组样式 */
:deep(.ant-radio-group) {
    display: flex;
    gap: 16px;
}

:deep(.ant-radio-wrapper) {
    margin-right: 0;
}

/* 优化文本域样式 */
:deep(.ant-textarea) {
    min-height: 100px;
}

/* 优化日期选择器样式 */
:deep(.ant-picker) {
    width: 100%;
}

/* 优化必填项标记 */
:deep(.ant-form-item-required::before) {
    color: #ff4d4f;
    margin-right: 4px;
}

/* 优化错误提示 */
:deep(.ant-form-item-explain) {
    font-size: 12px;
    margin-top: 4px;
    color: #ff4d4f;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
    :deep(.ant-modal) {
        width: 90% !important;
    }

    :deep(.ant-form-item-label) {
        text-align: left;
        padding-bottom: 8px;
    }

    :deep(.ant-form-item-label > label) {
        font-size: 14px;
    }

    :deep(.ant-input),
    :deep(.ant-input-number),
    :deep(.ant-picker) {
        font-size: 14px;
    }
}
</style>